import myAxios from '../myAxios/myAxios.js';
import myAxios28 from '../myAxios/myAxios28.js';
import myAxiosWXPost from '../myAxios/myAxiosWXPost.js';

import myArr from '../myAxios/myArr.js';
let { GetNumber } = myArr;

import { GetWaiXiaoOutPut_JJQQ } from './GetWaiXiaoOutPut_JJQQ.js';
import { GetJXSOutPut } from './GetJXSOutPut.js';
import { GetDHWJTable } from './GetDHWJTable.js';
import { GetSHWTTable } from './GetSHWTTable.js';
let GetWaiXiaoOutPut = async function () {
	// 假设已存在以下全局或导入的依赖项：
	// - client.unClearSalePo_AnXin (用于调用SAP接口获取JSON字符串)
	// - CommonTools.RunSqlHelper.Query (用于执行SQL查询)
	// - GetWaiXiaoOutPut_JJQQ (用于计算紧急欠缺数量的函数)
	// - GetJXSOutPut (用于获取机械手输出数据的函数)
	// - p100139Con, p100140Con (数据库连接字符串)
	// - matcodeWGZ_WX_Dic (一个已存在的字典，包含物料编码和对应的外销已发货数量)

	// 1. 调用SAP接口获取数据并解析JSON
	let root;
	let content = {
		xswerks: 'Q902',
		kcwerks: 'Q902',
		lgorts: '1007,1008,3001,3003,3006,7001',
		matcode: 'C1500026',
		sonmatcode: '',
	};

	const resultJson = await myAxiosWXPost.get(`http://192.168.100.28:44348/`, `unClearSalePo_AnXin`, content);
	console.log('resultJson :>> ', resultJson);
	root = resultJson;

	// 2. 获取紧急欠缺数量表 (假设GetWaiXiaoOutPut_JJQQ函数已实现或需导入)
	let unClearSalePoTable_JJQQ;
	try {
		unClearSalePoTable_JJQQ = await GetWaiXiaoOutPut_JJQQ(root);
	} catch (error) {
		console.error("获取紧急欠缺数量表失败:", error);
		unClearSalePoTable_JJQQ = []; // 出错时设置为空数组
	}

	// 3. 初始化主表结构 (模拟C#的DataTable及其Columns)
	const unClearSalePoTable = []; // 我们将构建一个对象数组

	// 4. 按物料号分组汇总销售数据 (模拟C#的GroupBy和Select)
	if (root && root.销售 && Array.isArray(root.销售)) {
		const groupedByMatnr = {};
		for (const saleItem of root.销售) {
			const key = saleItem.物料号;
			if (!groupedByMatnr[key]) {
				groupedByMatnr[key] = {
					MATNR: key,
					LSMENG2: 0,
					BHQTY: 0,
					OUTCOUNT_WAIXIAO: 0, // 初始值
					JJQQ: 0, // 初始值
					OUTCOUNT_JXS: 0  // 初始值
				};
			}
			// 累加LSMENG2: 如果PROPERTIES包含"内销"则加0，否则加未交货数量
			const quantity = saleItem.PROPERTIES && saleItem.PROPERTIES.includes("内销") ? 0 : (GetNumber(saleItem.未交货数量));
			groupedByMatnr[key].LSMENG2 += quantity;
			// BHQTY 保持为0 (根据C#代码)
		}
		// 将分组对象转换为数组
		Object.values(groupedByMatnr).forEach(item => {
			unClearSalePoTable.push(item);
		});
	}

	// 5. 获取并合并机械手输出数据 (JXSList)
	let JXSList;
	try {
		JXSList = await GetJXSOutPut(); // 假设此函数返回一个Promise，解析为DD对象数组
	} catch (error) {
		console.error("获取机械手输出数据失败:", error);
		JXSList = [];
	}

	for (const jxsItem of JXSList) {
		// 在主表中查找对应物料号的行
		const existingRow = unClearSalePoTable.find(row => row.MATNR === jxsItem.MATNR);
		if (existingRow) {
			existingRow.OUTCOUNT_JXS = GetNumber(jxsItem.OUTCOUNT_JXS);
		} else {
			// 如果主表中没有，则添加新行
			unClearSalePoTable.push({
				MATNR: jxsItem.MATNR,
				LSMENG2: 0,
				BHQTY: 0,
				OUTCOUNT_WAIXIAO: 0,
				JJQQ: 0,
				OUTCOUNT_JXS: GetNumber(jxsItem.OUTCOUNT_JXS)
			});
		}
	}

	// 6. 执行多个数据库查询并进行复杂的业务逻辑调整
	let dhwjTable = []; // 到货未检表
	let shTable = [];   // 售后未提表

	// 6.1 查询到货未检数据
	dhwjTable = await GetDHWJTable();

	// 6.2 查询售后未提数据
	shTable = await GetSHWTTable();

	// 6.3 遍历主表，进行复杂的加减法调整
	for (const row of unClearSalePoTable) {
		// 6.3.1 获取该物料的紧急欠缺初始值 (从unClearSalePoTable_JJQQ中查找)
		let outCount_JJQQ = 0;
		const jjqqRow = unClearSalePoTable_JJQQ.find(r => r.MATNR === row.MATNR);
		if (jjqqRow) {
			outCount_JJQQ = GetNumber(jjqqRow.JJQQ);
		}
		// 根据C#逻辑：outCount_JJQQ = outCount_JJQQ + Convert.ToDecimal(row["BHQTY"]);
		// 但row.BHQTY始终为0，所以此步可简略
		outCount_JJQQ += GetNumber(row.BHQTY);

		// 6.3.2 计算外销出仓初始值
		let outCount_WaiXiao = (GetNumber(row.LSMENG2)) + (GetNumber(row.BHQTY)); // LSMENG2 + BHQTY

		// 6.3.3 获取机械手出仓值
		const outCount_JXS = GetNumber(row.OUTCOUNT_JXS);

		// 6.3.4 初步设置JJQQ和OUTCOUNT_WAIXIAO
		row.JJQQ = outCount_JJQQ + outCount_JXS;
		row.OUTCOUNT_WAIXIAO = outCount_WaiXiao + outCount_JXS;

		// 6.3.5 减去到货未检数量
		const dhwjRows = dhwjTable.filter(dhwjRow => dhwjRow.MATNR === row.MATNR);
		for (const dhwjRow of dhwjRows) {
			const dhwjQTY = GetNumber(dhwjRow.QTY);
			row.JJQQ = (GetNumber(row.JJQQ)) - dhwjQTY;
			row.OUTCOUNT_WAIXIAO = (GetNumber(row.OUTCOUNT_WAIXIAO)) - dhwjQTY;
		}

		// 6.3.6 加上售后未提数量
		const shRows = shTable.filter(shRow => shRow.MATNR === row.MATNR);
		for (const shRow of shRows) {
			const SHQTY = GetNumber(shRow.SHNUM);
			row.JJQQ = (GetNumber(row.JJQQ)) + SHQTY;
			row.OUTCOUNT_WAIXIAO = (GetNumber(row.OUTCOUNT_WAIXIAO)) + SHQTY;
		}

		// (可选) 6.3.7 减去已发货数量 (根据注释，此逻辑已被注释掉)
		// if (matcodeWGZ_WX_Dic && matcodeWGZ_WX_Dic[row.MATNR]) {
		//     row.OUTCOUNT_WAIXIAO = (GetNumber(row.OUTCOUNT_WAIXIAO)) - matcodeWGZ_WX_Dic[row.MATNR];
		// }
	}

	// 7. 处理未在主表中出现但存在于shTable中的物料号
	for (const shRow of shTable) {
		const MATNR = shRow.MATNR;
		const exists = unClearSalePoTable.some(row => row.MATNR === MATNR);
		if (!exists) {
			const SHQTY = GetNumber(shRow.SHNUM);
			unClearSalePoTable.push({
				MATNR: MATNR,
				LSMENG2: 0,
				BHQTY: 0,
				OUTCOUNT_WAIXIAO: SHQTY,
				JJQQ: SHQTY,
				OUTCOUNT_JXS: 0
			});
		}
	}

	// 8. 返回最终处理后的数据
	console.log('GetWaiXiaoOutPut :>> ', unClearSalePoTable);
	return unClearSalePoTable;
};


export {
	GetWaiXiaoOutPut,
};